package com.jiangdg.demo

import CreatePatientPopup
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.media.MediaMetadataRetriever
import android.media.tv.TvView
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.gyf.immersionbar.ImmersionBar
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

class FileListActivity : AppCompatActivity() {

    private var immersionBar: ImmersionBar? = null

    private var fileGroupAdapter:FileGroupAdapter? = null
    private var tvName:TextView? = null
    private var ivEdit:ImageView? = null

    private  var tvDeleteTip:TextView? = null
    private var tvDelete:TextView? = null
    private var tvSaveAll:TextView? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStatusBar()
        setContentView(R.layout.activity_file_list)

        tvSaveAll = findViewById(R.id.tvSaveAll)
        tvSaveAll?.setOnClickListener {
            fileGroupAdapter?.saveAllSelected()
        }
        tvDeleteTip = findViewById(R.id.tvDeleteTip)
        tvDelete = findViewById(R.id.tvDelete)
        tvDeleteTip?.setOnClickListener {
            fileGroupAdapter?.toggleModel()
        }
        tvDelete?.setOnClickListener {
            fileGroupAdapter?.deleteSelectedItems()
            fileGroupAdapter?.toggleModel()
        }
        tvName = findViewById(R.id.tvName)
        ivEdit = findViewById(R.id.ivEdit)
        findViewById<ImageView>(R.id.ivBack).setOnClickListener { finish() }

        val folderPath = intent.getStringExtra(EXTRA_FOLDER_PATH)
        println(folderPath)
        val recyclerView: RecyclerView = findViewById(R.id.file_recycler_view)
        recyclerView.layoutManager = LinearLayoutManager(this)
        fileGroupAdapter = FileGroupAdapter(this, listOf(),object : FileGroupAdapter.OnItemSelectListener{
            override fun onEditModelChange(file: Boolean) {
                if(file){
                    tvDelete?.visibility = View.VISIBLE
                    tvSaveAll?.visibility = View.VISIBLE
                    tvDeleteTip?.visibility = View.GONE
                }else{
                    tvDelete?.visibility = View.GONE
                    tvSaveAll?.visibility = View.GONE
                    tvDeleteTip?.visibility = View.VISIBLE
                }
            }
        })
        recyclerView.adapter = fileGroupAdapter


        loadData(folderPath?:"")

    }

    private fun loadData(folderPath: String){
        println(folderPath)
        val folder = File(folderPath)
        var files = folder.listFiles() ?: emptyArray()
        files = files.sortedByDescending { it.lastModified() }.toTypedArray()

        val fileGroups = groupFilesByDate(files)

        tvName?.text = folder.name.replace("~~~","    ")

        ivEdit?.setOnClickListener {
            val createPatientPopup = CreatePatientPopup(this, folder.name,object : CreatePatientPopup.OnCreateSuccessListener{
                override fun onSuccess(name: String) {

                }

                override fun onEditSuccess(name: String) {
                    loadData("${filesDir}${File.separator}users${File.separator}${name}")
                    tvName?.text = name.replace("~~~","    ")
                    FolderRenameBroadcast.sendBroadcast(this@FileListActivity)
                }
            })
            createPatientPopup.showPopupWindow()
        }

        fileGroupAdapter?.setData(fileGroups)
    }


    private fun groupFilesByDate(files: Array<File>): List<FileGroup> {
        val dateFormatter = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
        val groupedFiles = files.groupBy { dateFormatter.format(Date(it.lastModified())) }
        return groupedFiles.map {
            val filesTemp = mutableListOf<File>()
            it.value.forEach{
                file->
                filesTemp.add(file)
            }
            FileGroup(it.key, filesTemp)
        }.sortedByDescending { it.date }
    }

    override fun onDestroy() {
        super.onDestroy()
        immersionBar= null
    }

    private fun setStatusBar() {
        immersionBar = ImmersionBar.with(this)
            .statusBarDarkFont(true)
            .statusBarColor(R.color.white)
            .navigationBarColor(R.color.white)
            .fitsSystemWindows(true)
            .keyboardEnable(true)
        immersionBar?.init()
    }
    companion object {
        private const val EXTRA_FOLDER_PATH = "extra_folder_path"

        fun createIntent(context: Context, folderPath: String): Intent {
            return Intent(context, FileListActivity::class.java).apply {
                putExtra(EXTRA_FOLDER_PATH, folderPath)
            }
        }
    }
}
